package com.zy.struts.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zy.struts.domain.Message;
import com.zy.struts.domain.User;
import com.zy.struts.util.HibernateSessionFactory;

public class MessageDAOImpl implements MessageDAO {

	public void addMessage(Message msg) {
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			Transaction tx = session.beginTransaction();
			session.save(msg);
			tx.commit();

		} finally {
			if (null != session)
				session.close();
		}
	}

	public List<Message> getMessages(User reciver) {
		List<Message> list = new ArrayList<Message>();
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			Transaction tx = session.beginTransaction();
			Query query = session
					.createQuery("from Message where reciverId=:reciverId");
			query.setEntity("reciverId", reciver);
			list = query.list();
			tx.commit();

		} finally {
			if (null != session)
				session.close();
		}
		return list;
	}

}
